package com.atguigu.scw.manager.listener;

import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

/**
 * 项目启动的时候，将一些常用数据放在application域中
 */
public class MyAppListener implements ServletContextListener {
    private static final Logger logger = LoggerFactory.getLogger(MyAppListener.class);

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        logger.debug("当前应用上下文路径：{}", servletContext.getContextPath());
        // 1 将项目路径放在application域中
        servletContext.setAttribute("ctp", servletContext.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // 2 项目关闭，销毁数据

        // Tomcat关闭时报错【驱动程序已被强制取消注册】【内存泄漏】【连接未能停止】-问题
        // 这里如果Web应用拥有多个数据库的连接，可以一并关闭
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        Driver d = null;
        while (drivers.hasMoreElements()) {
            try {
                d = drivers.nextElement();
                DriverManager.deregisterDriver(d);
                logger.warn(String.format("Driver %s deregister", d));
            } catch (SQLException ex) {
                logger.warn(String.format("Error deregister driver %s", d), ex);
            }
        }
        AbandonedConnectionCleanupThread.uncheckedShutdown();
    }
}
